package com.gl.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gl.entity.EduCourse;
import com.gl.entity.TOrder;
import com.gl.service.impl.TOrderServiceImpl;
import com.gl.utils.CommonResponse;
import com.gl.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-12-14
 */
@RestController
@RequestMapping("/order")
public class TOrderController {
    @Autowired
    private TOrderServiceImpl orderService;

    /**
     * 分页查询订单
     * @param current
     * @param size
     * @return
     */
    @PostMapping("getOrder/{current}/{size}")
    public Map getPageList(@PathVariable long current,
                           @PathVariable long size){
        Map<String,Object> map = orderService.getPageList(current,size);
        return map;
    }

    //立即购买课程，生成订单，返回生成的订单号
    @PostMapping("buyCourse")
    public String buyCourse(@RequestBody TOrder order, HttpServletRequest request){
        String orderNo = orderService.saveOrder(order, request);
        return orderNo;
    }

    //根据订单号查询订单
    @GetMapping("getInfoByOrderNo/{orderNo}")
    public TOrder getInfoByOrderNo(@PathVariable String orderNo){
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        TOrder order = orderService.getOne(wrapper);
        return order;
    }

    //查询用户是否买过课程
    @GetMapping("isBuyCourse/{courseId}")
    public boolean isBuyCourse(@PathVariable String courseId,
                               HttpServletRequest request){

        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        //根据课程id和用户id以及课程状态判断用户是否购买过课程
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id", JwtUtils.getMemberIdByJwtToken(request));
        wrapper.eq("status",1);
        int count = orderService.count(wrapper);
        if(count>0){
            return true;
        }

        return false;
    }

    //---------------------------------------后台------------------------------------------------

    //查订单列表
    @PostMapping("getOrderList/{limit}/{size}")
    public CommonResponse getOrderList(@PathVariable long limit,
                                       @PathVariable long size,
                                       @RequestBody(required = false) TOrder order) {
        Page<TOrder> page = new Page<>(limit, size);
        Map<String, Object> map = orderService.getOrderList(page, order);
        return CommonResponse.ok().data(map);
    }
}

